package de.grosjohann.android.feuerwehr.webservice;

import java.io.IOException;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class WsClient {

  public static final String MEDIA_TYPE = "application/json";

  protected final HttpClient hc;
  protected final String uri;

  WsClient(String newUri, int connectionTimeout, int socketTimeout) throws ClientProtocolException, IOException {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    hc = new DefaultHttpClient(httpParameters);
    uri = newUri;
  }

  String get() throws ClientProtocolException, IOException, HttpException {
    HttpGet httpGet = new HttpGet(uri);
    httpGet.setHeader("Accept", WsClient.MEDIA_TYPE);
    HttpResponse resp = hc.execute(httpGet);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      return EntityUtils.toString(resp.getEntity());
    }

    throw new HttpException(httpGet.getURI().toString() + " " + resp.getStatusLine().getReasonPhrase() + " ("
        + resp.getStatusLine().getStatusCode() + ")");
  }

}
